package com.atguigu.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.constant.MessageConstant;
import com.atguigu.pojo.OrderSetting;
import com.atguigu.service.OrderSettingService;
import com.atguigu.utils.POIUtils;
import com.atguigu.vo.Result;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.ws.rs.POST;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @program: meinian_parent
 * @author: Mr.Zhuo
 * @create: 2022-02-16 17:32
 **/
@RestController
@RequestMapping("/orderSetting")
public class OrderSettingController {

    @Reference
    OrderSettingService orderSettingService;

    @PostMapping("/editNumberByDate")
    public Result editNumberByDate(@RequestBody OrderSetting orderSetting) {
        try {
            orderSettingService.editNumberByDate(orderSetting);
            return new Result(true, MessageConstant.ORDERSETTING_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true, MessageConstant.ORDERSETTING_FAIL);
        }
    }

    @GetMapping("/getOrderSettingByMonth")
    public Result getOrderSettingByMonth(String data) {
        try {
            List<Map<String, Object>> list = orderSettingService.getOrderSettingByMonth(data);
            return new Result(true, MessageConstant.GET_ORDERSETTING_SUCCESS, list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_ORDERSETTING_FAIL);
        }
    }

    @PostMapping("/upload")
    public Result upload(@RequestBody MultipartFile excelFile) {
        // 接受数据，调用工具类
        try {
            List<String[]> strings = POIUtils.readExcel(excelFile);
            // 然后把咱们的数据解析成实体对象
            ArrayList<OrderSetting> dataList = new ArrayList<>();
            for (String[] string : strings) {
                OrderSetting orderSetting = new OrderSetting();
                orderSetting.setOrderDate(new Date(string[0]));
                orderSetting.setNumber(Integer.parseInt(string[1]));
                orderSetting.setReservations(0);
                dataList.add(orderSetting);
            }

            // 然后进行数据持久化保存
            orderSettingService.upload(dataList);
            return new Result(true, MessageConstant.GET_ORDERSETTING_SUCCESS);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_ORDERSETTING_FAIL);
        }
    }
}
